#include "DiffuseShader.h"


DiffuseShader::DiffuseShader(float _amount, vec4 _color):SurfaceShader(_amount){
	diffuseColor = _color;
}


DiffuseShader::~DiffuseShader(){
}


vec4 DiffuseShader::getColor(Intersection &_int, Scene* _s){
	//check for max bounce depth
	if (_int.ray()->depth() == _int.ray()->maxDepth()){
		return vec4(0, 0, 0, 0);
	}

	vec4 retColor = vec4(0,0,0,0);
	vector<Light*>::iterator lights = _s->lights();	//lights in the scene
	
	Ray *theRay = _int.ray();
	int numLights = _s->lightCount();
	int numShapes = _s->shapeCount();
	vec4 pt = _int.getPos();						//intersection point
	vec4 norm = _int.surfNorm();					//surface normal
	//for each light
	for (int i = 0; i < numLights; i++){
		Light *theLight = *lights;

		//fire a ray toward the light	
		vec4 toLight = theLight->position() - pt;
		vec4 l_norm = normalize(toLight);
		Ray *shadowRay = new Ray(pt, l_norm, theRay->maxDepth(), theRay->depth() + 1, 1);
		Intersection _int2 = Intersection(shadowRay);
		
		//get a pointer to the BVH
		BVH* _bvh = _s->theBVH();
		_bvh->intersect(_int2);
		

		/*//THE OLD WAY
		vector<Shape*>::iterator shapes = _s->shapes();	//shapes in the scene
		for (int s = 0; s < numShapes; s++){
			Shape *nextShape = *shapes;
			nextShape->intersect(_int2);
			shapes++;
		}
		//END THE OLD WAY*/

		float distToLight = length(toLight);
		//if the ray hits the light before anything else
		if (!_int2.intersected()){
			//calculate the light that strikes the surface
			//add it into retColor
			retColor += dot(l_norm, norm) * theLight->intensity() * diffuseColor;
		}
		else if (_int2.intersected() && _int2.dist() > distToLight){
			retColor += dot(l_norm, norm) * theLight->intensity() * diffuseColor;
		}
				
		lights++;
		delete shadowRay;
	}
	return retColor * this->amount();
	//calculate the diffuse contribution from this point
	return vec4(0, 1, 0, 0);
}
